package Netty之NIO背景.MultiThread;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;

import static Netty之NIO背景.c1.ByteBufferUtil.debugAll;

/**多线程优化版NIO服务端
 * TODO：仔细听一下视频的p43 link：https://www.bilibili.com/video/BV1py4y1E7oA?p=44&spm_id_from=pageDriver
 * @author ChenweiLin
 * @create 2021-12-07 17:25
 */
@Slf4j
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();//打开网络套接字通道
        ssc.configureBlocking(false);//设置为非阻塞模式
        Selector boss = Selector.open();//创建选择器
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));

        //1.创建固定数量的worker并初始化
        Worker worker = new Worker("worker-0");

        while (true){
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()){
                SelectionKey key = iter.next();
                iter.remove();
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}", sc.getRemoteAddress());
                    //2. 关联 worker 的 Netty之NIO背景.selector
                    log.debug("before register...{}", sc.getRemoteAddress());
                    worker.register(sc);//仍然是在boss线程重执行的
                    log.debug("after register...{}", sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;//是否初始化的标志，false为还未初始化
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        //初始化线程和选择器
        public void register(SocketChannel sc) throws IOException {
            if (!start){
                thread = new Thread(this,name);//线程的任务this，即本对象就是线程的任务
                selector = Selector.open();
                thread.start();//线程启动
                start = true;
            }
            //向队列添加了任务，但这个任务并没有立即执行
            queue.add(()->{
                try {
                    sc.register(selector, SelectionKey.OP_READ,null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            selector.wakeup();//唤醒select方法
        }


        @Override
        public void run() {
            //检测读写事件
            while (true){
                try {
                    selector.select();//worker-0 阻塞，wakeup
                    Runnable task = queue.poll();
                    if(task != null)
                        task.run();//执行了sc.register(Netty之NIO背景.selector, SelectionKey.OP_READ,null);在worker-0线程中执行
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {//可读事件
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel)key.channel();
                            log.debug("read...{}", channel.getRemoteAddress());
                            channel.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
